function add_watermark(html, watermark)
    -- JavaScript代码，用于在页面上添加水印
    local js_code = [[
    <script type="text/javascript"> 

    var watermarkContainer = document.createElement('div');
    function createContainer (data){
        watermarkContainer.style.position = 'fixed';
        watermarkContainer.style.top = '0';
        watermarkContainer.style.left = '0';
        watermarkContainer.style.width = '100%';
        watermarkContainer.style.height = '100%';
        watermarkContainer.style.pointerEvents = 'none';
        watermarkContainer.style.zIndex = '9999';
        watermarkContainer.setAttribute('id', 'example-content')
        fillWatermarks(data)
    }

    // 水印样式设置
    function createWatermark(data) {
        var watermarkText = 'test';
        const info = JSON.parse(data)
        var watermarkDiv = document.createElement('div');
        watermarkDiv.style.position = 'absolute';
        watermarkDiv.style.color = 'rgba(141, 134, 134, 0.15)'; // 调整颜色和透明度
        watermarkDiv.style.fontSize = '20px'; // 字体大小
        watermarkDiv.style.transform = 'rotate(-45deg)'; // 旋转角度
        watermarkDiv.style.whiteSpace = 'nowrap';
        watermarkDiv.className = 'water-class-name';
        watermarkDiv.innerText = renderedString(info);
        return watermarkDiv;
    }
    function renderedString (info){
        let renderedString = '';
        for (const [key, value] of Object.entries(info)) {
          switch (key) {
            case 'time':
              // 特殊处理时间属性，将其转换为日期对象并格式化
              const formattedTime = formatDate(new Date(value), 'yyyy-MM-dd HH:mm:ss');
              renderedString += `${formattedTime}\n`;
              break;
            default:
              // 对于其他属性，直接输出属性名和值
              renderedString += `${value}\n`;
          }
        }
        return renderedString
    }
    // 根据屏幕大小填充水印
    function fillWatermarks(data) {
        // 清空之前的水印
        watermarkContainer.innerHTML = '';
        var screenWidth = window.innerWidth;
        var screenHeight = window.innerHeight;
        var watermarkWidth = 300; // 水印宽度
        var watermarkHeight = 400; // 水印高度

        for (let x = 0; x < screenWidth; x += watermarkWidth) {
            for (let y = 0; y < screenHeight; y += watermarkHeight) {
                let watermarkDiv = createWatermark(data);
                watermarkDiv.style.left = x + 'px';
                watermarkDiv.style.top = y + 'px';
                watermarkContainer.appendChild(watermarkDiv);
            }
        }
    }
    function getWaterInfo(){
        const action = window.location.origin
        fetch(`${action}/aaa/getWaterInfo`)
        .then(response => {
            if (!response.ok) {
            throw new Error('Network response was not ok.');
            }
            return response.text();  // 或者 response.json() 如果返回JSON数据
        })
        .then(data => {
            // 处理成功响应数据
            createContainer(data)
            document.body.appendChild(watermarkContainer);
        })
        .catch(error => {
            // 处理请求错误
            console.error('Error:', error);
        })
    }
    function formatDate(date, formatString) {
        const replacements = {
          'yyyy': date.getFullYear(),
          'yy': String(date.getFullYear()).slice(-2),
          'MM': String(date.getMonth() + 1).padStart(2, '0'),
          'M': date.getMonth() + 1,
          'dd': String(date.getDate()).padStart(2, '0'),
          'd': date.getDate(),
          'HH': String(date.getHours()).padStart(2, '0'),
          'H': date.getHours(),
          'mm': String(date.getMinutes()).padStart(2, '0'),
          'm': date.getMinutes(),
          'ss': String(date.getSeconds()).padStart(2, '0'),
          's': date.getSeconds(),
        };
      
        return formatString.replace(/(\w{2,})/g, (match, key) => replacements[key] || match);
      }
    window.onresize = fillWatermarks;
    window.onload = function () {
        getWaterInfo()
        const timerId =  setInterval(function() {
            getWaterInfo()
        }, 5000)
    }
     // 添加页面卸载时的事件监听器，清除定时器
    window.addEventListener('beforeunload', function (event) {
        clearInterval(timerId);
    })
    </script>
    ]]
    return html:gsub("</body>", js_code .. "</body>")
end

local edit_js = function(response,uname)

    local js_addition = [[

        console.log('%c XSJ-[  ]-67', 'font-size:13px; background:pink; color:#bf2c9f;', '钱钱钱’钱钱')
        // 你想添加的JavaScript代码
        let name = '许世杰'
        // 设置一个60秒执行一次的定时器模拟请求
        window.lu= '' 
        console.log(window.lu,111)
        if(window.lu){
            clearInterval(window.lu);
        }
        var cont = 0
        window.lu = setInterval(function() {
            console.log('定时器触发了！');
            name += '安'
            cont ++ 
            console.log('%c XSJ-[ cont ]-95', 'font-size:13px; background:pink; color:#bf2c9f;', cont)
            createContainer(name)
            // 在某个条件满足时停止定时器
            if (false) {//目前恒不成立，需要使用写入成立条件
                clearInterval(timerId);
            }
        }, 10000);
        const action = window.location.origin
        console.log('%c XSJ-[ cont ]-86', 'font-size:13px; background:pink; color:#bf2c9f;', cont)
        fetch(`${action}/aaa/getWaterInfo`)
        .then(response => {
            if (!response.ok) {
            throw new Error('Network response was not ok.');
            }
            return response.text();  // 或者 response.json() 如果返回JSON数据
        })
        .then(data => {
            // 处理成功响应数据
            console.log(data);
        })
        .catch(error => {
            // 处理请求错误
            console.error('Error:', error);
        })
        if (document.getElementById('example-content')) {
            document.getElementById('example-content').remove()
        }
        var divs = document.getElementsByClassName('water-class-name');
        if(divs){
            for (let i = 0; i < divs.length; i++) {
                var element = divs[i];
                element.remove();
            }
        }
        function createContainer (name){
        var watermarkContainer = document.createElement('div');
        watermarkContainer.style.position = 'fixed';
        watermarkContainer.style.top = '0';
        watermarkContainer.style.left = '0';
        watermarkContainer.style.width = '100%';
        watermarkContainer.style.height = '100%';
        watermarkContainer.style.pointerEvents = 'none';
        watermarkContainer.style.zIndex = '9999';
        watermarkContainer.setAttribute('id', 'example-content')
        // 水印样式设置
        function createWatermark() {
            var watermarkText = 'test';
            var watermarkDiv = document.createElement('div');
            watermarkDiv.style.position = 'absolute';
            watermarkDiv.style.color = 'rgba(255, 0, 0, 0.4)'; // 调整颜色和透明度
            watermarkDiv.style.fontSize = '20px'; // 字体大小
            watermarkDiv.style.transform = 'rotate(-45deg)'; // 旋转角度
            watermarkDiv.style.whiteSpace = 'nowrap';
            watermarkDiv.className = 'water-class-name';
            watermarkDiv.innerText = `${name}`;
            return watermarkDiv;
        }
    
        // 根据屏幕大小填充水印
        function fillWatermarks() {
            // 清空之前的水印
            watermarkContainer.innerHTML = '';
            var screenWidth = window.innerWidth;
            var screenHeight = window.innerHeight;
            var watermarkWidth = 300; // 水印宽度
            var watermarkHeight = 400; // 水印高度
    
            for (var x = 0; x < screenWidth; x += watermarkWidth) {
                for (var y = 0; y < screenHeight; y += watermarkHeight) {
                    var watermarkDiv = createWatermark();
                    watermarkDiv.style.left = x + 'px';
                    watermarkDiv.style.top = y + 'px';
                    //watermarkContainer.appendChild(watermarkDiv);
                }
            }

            console.log('%c XSJ-[  ]-152', 'font-size:13px; background:pink; color:#bf2c9f;', '执行了')
        }
    
        // 当窗口大小改变时，重新填充水印
        window.onresize = fillWatermarks;
    
        document.body.appendChild(watermarkContainer);
        fillWatermarks(); // 初始填充水印
        console.log('%c XSJ-[  ]-152', 'font-size:13px; background:pink; color:#bf2c9f;', '执行了')
        }
    ]]
    return  response .. js_addition
end

local getTime = function ()
    -- 获取当前的时间戳，以秒为单位
    local seconds = ngx.time()

    -- 使用os.date()将时间戳格式化为可读的日期和时间
    -- %Y-%m-%d %H:%M:%S 是日期和时间的格式化字符串
    -- %Y 表示四位年份，%m 表示月份（01-12），%d 表示日期（01-31）
    -- %H 表示小时（24小时制），%M 表示分钟，%S 表示秒
    local formatted_time = os.date("%Y-%m-%d %H:%M:%S", seconds)
    return formatted_time
end


local unzipBody = function(body)
    local zlib = require "zlib"  -- 加载zlib库
    if not body or body == "" then return nil end
    local stream = zlib.inflate()
    local status, result = pcall(stream, body)
    if status then
        return result
    else
        ngx.log(ngx.ERR, "Failed to ungzip body: ", result)
        return nil
    end
end

-- 后面待改造，主要是针对gzip的响应进行压缩
function gzip(body)
    local zlib = require("zlib")
    local windowSize = 15+16
    local stream = zlib.deflate(5,windowSize)  -- 使用gzip而不是deflate
    local status, result = pcall(stream, body, "finish")
    if status then
        return result
    else
        ngx.log(ngx.ERR, "Failed to gzip body: ", result)
        return nil
    end
end



function main()
        -- 从ngx.arg数组获取当前的响应块内容和是否为最后一个响应块的标志。
        local chunk, eof = ngx.arg[1], ngx.arg[2]
        -- 从ngx.ctx获取buffered变量，用于缓存响应块。
        local buffered = ngx.ctx.buffered

        -- 如果buffered变量未初始化，则初始化为一个空表。
        if not buffered then
            buffered = {}
            ngx.ctx.buffered = buffered
        end

     -- 如果eof为true，表示这是最后一个响应块。
    if eof then

        local content_type = ngx.header["Content-Type"] 
       

        -- 将所有缓存的响应块连接成一个完整的响应。
        local response = table.concat(buffered)

        -- ngx.log(ngx.ERR, "content_type--%%%%%%%%%%%- ", content_type)
        -- local response_base64 = ngx.encode_base64(response)
        -- ngx.log(ngx.ERR, "response--%%%%%%%--- ", response_base64)

        local shared_data = ngx.shared.user_data
        -- 获取所有的键
        local keys = shared_data:get_keys()

        for _, key in ipairs(keys) do
            -- 获取与键关联的值
            local value = shared_data:get(key)
            -- 打印键和值
            ngx.log(ngx.ERR, "Key-------: ", key, " Value------: ", tostring(value))
        end

        local appid = ngx.var.app_id

        -- 组合键：客户端IP地址和appid
        local key_arr = ngx.var.remote_addr .. "_" .. (appid or "default")

        local username = shared_data:get(key_arr) or "云智信安"  -- 从共享内存获取用户名
        local remote_addr = ngx.var.remote_addr
        local time = getTime()

        local water_info = username .. remote_addr .. time

        -- ngx.log(ngx.ERR,"key_arr+++++++++++++++",key_arr, "############username-XXXX ", water_info)

        local watermark_text = water_info or "默认水印"  -- 如果没有用户名，则使用默认水印
            -- 只针对html做判断修改
        if content_type ~= nil and content_type:match("text/html") then

            ngx.log(ngx.ERR, "text/html-----response ", response)
            local content_encoding = ngx.resp.get_headers()["Content-Encoding"]
            if content_encoding == "gzip" then
                ngx.log(ngx.ERR, "response--- gzip压缩的text/html响应体")
                local uncompressed_html = unzipBody(response)
                response = uncompressed_html
                ngx.log(ngx.ERR, "unzipd-----response ", uncompressed_html)
                if response:match("<html") then
                    ngx.log(ngx.ERR, "edit_html---------------------------- ", watermark_text)
                    response = add_watermark(response, watermark_text)  -- 添加水印
                    ngx.log(ngx.ERR, "response====++befor ", response)
                    response = gzip(response)
                    ngx.log(ngx.ERR, "response====++after ", response)
                end
                -- 解压gzip压缩的响应体
            elseif content_encoding == "deflate" then
                ngx.log(ngx.ERR, "response--- deflate压缩text/html的响应体")
                -- 解压deflate压缩的响应体
            else
                ngx.log(ngx.ERR, "response--- 未被压缩的text/html响应体")
                -- 响应体未压缩，直接修改
                if response:match("<html") then
                    ngx.log(ngx.ERR, "edit_html---------------------------- ", watermark_text)
                    response = add_watermark(response, watermark_text)  -- 添加水印
                end
            end
            ngx.arg[1] = response

        elseif content_type ~= nil and content_type:match("application/javascript") then
                -- response = edit_js(response,watermark_text)
                -- ngx.log(ngx.ERR, "response--- ", response)


                local content_encoding = ngx.resp.get_headers()["Content-Encoding"]
                if content_encoding == "gzip" then
                    ngx.log(ngx.ERR, "response--- gzip压缩的application/javascript响应体")
                    -- 解压gzip压缩的响应体
                -- elseif content_encoding == "deflate" then
                --     ngx.log(ngx.ERR, "response--- deflate压缩application/javascript的响应体")
                --     -- 解压deflate压缩的响应体
                -- else
                --     ngx.log(ngx.ERR, "response--- 未被压缩的application/javascript响应体")
                    -- 响应体未压缩，直接修改
                end


                ngx.arg[1] = response
        else
            ngx.arg[1] = response
            -- ngx.log(ngx.ERR,"其他响应content_type----------------------- ", watermark_text)
            
        end
    else
            if chunk ~= "" then
                buffered[#buffered + 1] = chunk
            end
            ngx.arg[1] = nil
        
    end

    
end

main()
